from sqlalchemy import Column, Integer, String, UniqueConstraint
from sqlalchemy.orm import relationship
from sqlalchemy import Enum as SQLEnum
from db.model.base import Base
from db.model.enums import DeviceType


class Device(Base):
    __tablename__ = "device"

    id = Column(Integer, primary_key=True, comment="id")
    name = Column(String(32), nullable=False, unique=True, comment="设备名称")
    # 设备类型，如 TCP、RTU
    device_type = Column(SQLEnum(DeviceType, name="device_type"), nullable=False, comment="设备类型")
    ip = Column(String(32), comment="Ip地址")
    port = Column(Integer, comment="端口")
    serial_port = Column(String(32), comment="串口名称")
    baud_rate = Column(Integer, comment="波特率")
    data_bits = Column(Integer, comment="数据位")
    stop_bits = Column(Integer, comment="停止位")
    parity = Column(String(8), comment="校验位")
    protocol = Column(String(32), nullable=False, comment="通讯类型")

    # 关联从站
    slaves = relationship("Slave", back_populates="device")

    __table_args__ = (
        # TCP 设备唯一约束
        UniqueConstraint("ip", "port", name="uq_tcp_connection"),
        # 串口设备唯一约束
        UniqueConstraint("serial_port", name="uq_serial_connection"),
        {"comment": "设备表"}
    )
